import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
//import { Form, Icon, Upload, Cascader} from 'zent';
import { Spin ,Form, message,Cascader,Upload, Button,Icon, Card,Input,Row,Col} from 'antd';
import InputText from '@/components/Input/index';
import styles from './index.less';

@Form.create()
class FieldForm extends Component {
 
  state = {
    checkedList: [],
    value: [],
    storeLogo:'',
    imageUrl:''
  };
  componentDidMount() {
    const { dispatch, form } = this.props;   
    dispatch({
      type: 'storeinfo/GetIndustryList',
    });
    dispatch({
      type: 'storeinfo/GetStoreInfo',
      callback: {
        success: res => {
          if (res.Code == 0) {
            const { cdnUrl } = this.props;   
            console.log(cdnUrl,777)
            this.setState({
              imageUrl: res.Data ? `${cdnUrl}/${res.Data.StoreLogo}` : '',
              storeLogo:res.Data ? `${res.Data.StoreLogo}` : '',             
            });           
            form.setFieldsValue({
              StoreLogo:res.Data ? `${res.Data.StoreLogo}` : undefined,
              StoreName: res.Data ? res.Data.StoreName : '',
              Contacts: res.Data ? res.Data.Contacts : '',
              TelPhone: res.Data ? res.Data.TelPhone : '',
              Introduction: res.Data ? res.Data.Introduction : '',
              Industry: res.Data
                  ? [
                      res.Data.IndustryFirstId ? res.Data.IndustryFirstId : '',
                      res.Data.IndustrySecondId ? res.Data.IndustrySecondId : '',
                    ]
                  : [],
            })
          }
        },
      },
    });
  }

  getStoreInfo = () => {
    const { dispatch, form, cdnUrl } = this.props;
    const { setFieldsValue } = form;
    dispatch({
      type: 'storeinfo/GetStoreInfo',
      callback: {
        success: res => {
          if (res.Code == 0) {
            this.setState({
              fileList: [
                {
                  uid: '1',
                  key: 1,
                  url: res.Data ? res.Data.StoreLogo : '',
                },
              ],
              defaultValue: res.Data ? [res.Data.IndustryFirstId, res.Data.IndustrySecondId] : [],
              value: res.Data ? [res.Data.IndustryFirstId, res.Data.IndustrySecondId] : [],
              storeLogo:res.Data ? `${res.Data.StoreLogo}` : '',
            });
            setTimeout(() => {
              setFieldsValue({
                StoreLogo: res.Data ? `${cdnUrl}/${res.Data.StoreLogo}` : '',
                StoreName: res.Data ? res.Data.StoreName : '',
                Contacts: res.Data ? res.Data.Contacts : '',
                TelPhone: res.Data ? res.Data.TelPhone : '',
                Introduction: res.Data ? res.Data.Introduction : '',
                Industry: res.Data ? [res.Data.IndustryFirstId, res.Data.IndustrySecondId] : [],
              });
            });
          }
        },
      },
    });
  };
  handleSelectIcon = iconInfo => {
    this.setState({
      currentSelectedIconInfo: iconInfo,
    });
    this.hideModal('iconModalVisible');
  };
  hideModal(type) {
    this.setState({
      [`${type}`]: false,
    });
  }
  GetIndustryName = (id, arr) => {
    const { industryList } = this.props;
    let list = arr || industryList || [];
    if (id) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].value == id) {
          return list[i].label;
        } else {
          if (list[i].children) {
            for (let j = 0; j < list[i].children.length; j++) {
              if (list[i].children[j].value == id) {
                return list[i].children[j].label;
              }
            }
          }
        }
      }
    }
  };
  handleIconModalCancel = () => {
    this.hideModal('iconModalVisible');
  };
 
  handleChange = info => {
    const { oemInfo, dispatch } = this.props;
    if (info.file.status === 'uploading') {
      this.setState({
        loading: true,
        imageUrl: '',
      });
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response && info.file.response.Code === 0) {
        let imageUrl = info.file.response.Data.url;
        this.props.form.setFieldsValue({
          StoreLogo: imageUrl,
        });
        this.setState({
          imageUrl,
          loading: false,
          storeLogo:imageUrl,
        });
      } else {
        message.error('上传图片失败，请重新上传!');
        this.props.form.setFieldsValue({
          StoreLogo: '',
        });
        this.setState({
          imageUrl: '',
          loading: false,
        });
      }
    }
  };
  changeIndustry = e => {
    // console.log(9)
    console.log(e);
  };  

  onCheckboxChange = checkedList => {
    this.setState({ checkedList });
  };
  getImgInfo = src => {
    console.log(w, src);
    if (!src) {
      return;
    }
    var img = document.createElement('img'); //创建一个img元素
    img.src = src; //指定src
    img.style.position = 'absolute'; //防止正常的内容变形
    img.style.visibility = 'hidden'; //藏起来
    var inj = document.body.appendChild(img); //插入到box中。当然插入到document.body也可以
    let height = inj.offsetHeight;
    let width = inj.offsetWidth;
    document.body.removeChild(img);
    return { height, width };
  };
  submit = () => {
    const { dispatch, oemInfo,form } = this.props;  
    form.validateFieldsAndScroll((err,values)=>{  
      console.log(values)   
      if(err) return;
      console.log(values)
      dispatch({
        type: 'storeinfo/SaveStoreInfo',
        payload: {
        // StoreLogo: values.StoreLogo[0].src,
          StoreLogo:this.state.storeLogo,//'xkdnewyun/systemfile/images/f8350a5681fb42c480f2bdbf152361c1.jpg',
        //StoreLogo:'xkdnewyun/systemfile/images/f8350a5681fb42c480f2bdbf152361c1.jpg',
          StoreName: values.StoreName,
          Contacts: values.Contacts,
          TelPhone: values.TelPhone,
          Introduction: values.Introduction,
          IndustryFirst: this.GetIndustryName(values.Industry[0]),
          IndustryFirstId: values.Industry[0],
          IndustrySecond: this.GetIndustryName(values.Industry[1]),
          IndustrySecondId: values.Industry[1],
        },
        callback: {
          success: res => {
            if (res.Code == 0) {  
              message.success('保存成功');
              dispatch({
                type: 'storeinfo/GetStoreLogo',
                callback: {
                  success: res => {
                    if (res.Code == 0) {
                      oemInfo.storeLogo = res.Data.StoreLogo;
                      console.log(oemInfo,999)
                      dispatch({
                        type: 'global/setConfigData',
                        payload: {
                          oemInfo,
                        },
                      });
                    }
                  },
                },
              });            
            } else {
              message.error(res.Msg, 2);
            }
          },
        },
      });
    })    
  };

  resetForm = () => {
    this.props.zentForm.validateForm();
  };
  updateLocalImage = data => {       
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(data);
      }, 3000);
    });    
  };
  updateIndustry = e => {
    console.log(e);
    // let ids=[];
    // e.forEach((item)=>{
    //   ids.push(item.id);
    // })
    let ids = e.map(item => item.id);
    console.log(ids);
    this.setState(
      {
        value: ids,
      },
      () => {
        this.props.zentForm.setFieldsValue({
          Industry: ids,
        });
      }
    );
  };

  beforeUpload = (file) => {
    const isJPG = file.type === 'image/jpeg'||file.type === 'image/jpg'||file.type === 'image/png'||file.type === 'image/svg'||file.type === 'image/gif';
    if (!isJPG) {
      message.error('请选择正确的图片格式');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB');
    }
    return isJPG && isLt2M;
  }

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleUploadChange = info => {
    const {form} = this.props;
    this.setState({ loading: true });
    this.getBase64(info.file.originFileObj, imageUrl => {
        this.setState({
        imageUrl,
        storeLogo:imageUrl,
        loading: false,
      })
      form.setFieldsValue({
        StoreLogo:imageUrl,       
      })
    }
  );
  }

  render() {
    const { storeInfo, loading, submitLoading, industryList, cdnUrl,storeLogo,form:{getFieldDecorator} } = this.props;
    const { iconModalVisible, currentSelectedIconInfo, fileList, imageUrl } = this.state;   
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 8 },
        sm: { span: 8 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 8,
          offset: 6,
        },
        sm: {
          span: 8,
          offset: 6,
        },
      },
    };
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const { handleSubmit, zentForm } = this.props; 
    return (
      <Fragment>
        <Spin spinning={loading}>
          <Card bordered={false}>
            <div className={styles.storeinfo}>              
              <Form {...formItemLayout} onSubmit={this.handleSubmit}>        
                <Form.Item
                  label="店铺LOGO"
                >
                  {getFieldDecorator('StoreLogo', {
                    rules: [{ required: true, message: '请上传店铺LOGO' }],
                    validateTrigger:'onBlur'
                  })(
                    <Upload
                      name="avatar"
                      listType="picture-card"
                      className={styles["avatar-uploader"]}
                      showUploadList={false}
                      // action="//jsonplaceholder.typicode.com/posts/"
                      beforeUpload={this.beforeUpload}
                      onChange={this.handleUploadChange}
                    >
                      {imageUrl ? <img src={imageUrl} alt="LOGO" className="xkd-width-per-100" style={{height:'100%'}}/> : uploadButton}
                    </Upload>
                  )}
                </Form.Item>
                <Form.Item
                  label="店铺名称"
                >
                  {getFieldDecorator('StoreName', {
                    rules: [{ required: true, message: '请填写店铺名称', whitespace: true },{pattern:/^[a-zA-Z\u4E00-\u9FA5\uF900-\uFA2D\d]{2,20}$/,message:'店铺名称只能含有中英文、数字，最少2、最大20个字符'}],
                    validateTrigger:'onBlur'
                  })(
                    <InputText maxLength={20} showtotal/>
                  )}
                </Form.Item>
                <Form.Item
                  label="所属行业"
                >
                  {getFieldDecorator('Industry', {
                   // initialValue: ['zhejiang', 'hangzhou', 'xihu'],
                    rules: [{ required: true, message: '请选择所属行业' }],
                    //validateTrigger:'onBlur'
                  })(
                    <Cascader options={industryList} placeholder=""/>
                  )}
                </Form.Item>
                <Form.Item
                  label="手机号码"
                >
                  {getFieldDecorator('TelPhone', {
                    rules: [{ required: true, message: '请填写手机号码' },{pattern:/^1[2-9][\d]{9}$/,message:'请输入正确手机号码'}],
                    validateTrigger:'onBlur'
                  })(
                    <Input  style={{ width: '100%' }} />
                  )}
                </Form.Item>                
                <Form.Item
                  label="联系人"                  
                >
                  {getFieldDecorator('Contacts', {
                    rules: [{ required: true, message: '请填写联系人' },{pattern:/^[a-zA-Z\u4E00-\u9FA5\uF900-\uFA2D]{2,20}$/,message:'联系人只能输入中英文，字数在2~20个'}],
                    validateTrigger:'onBlur'
                  })(
                    <Input />
                  )}
                </Form.Item> 
                <Form.Item
                  label="店铺简介"
                >
                  {getFieldDecorator('Introduction')(
                    <InputText maxLength={60} showtotal type="textarea" rows={3}/>
                  )}
                </Form.Item>               
                <Form.Item {...tailFormItemLayout}>
                  <Button type="primary" onClick={this.submit} loading={submitLoading}>保存信息</Button>
                </Form.Item>
              </Form>
            </div>
          </Card>
        </Spin>
      </Fragment>
    );
  }
}

//const WrappedForm = createForm({ scrollToError: true })(FieldForm);


export default connect(({ global, storeinfo, loading }) => ({ 
  oemInfo: global.oemInfo,
  cdnUrl: global.oemInfo.cdnUrl,
  storeLogo:storeinfo.storeLogo,
  storeinfo,
  storeInfo: storeinfo.storeInfo,
  industryList: storeinfo.industryList,
  loading: loading.effects['storeinfo/GetStoreInfo'],
  submitLoading: loading.effects['storeinfo/SaveStoreInfo'],
}))(FieldForm);
